package com.hongyuan.sellfitness.ui.person.view_mode;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.hongyuan.mvvmhabitx.bus.event.SingleLiveEvent;
import com.hongyuan.sellfitness.BR;
import com.hongyuan.sellfitness.R;
import com.hongyuan.sellfitness.base.Constants;
import com.hongyuan.sellfitness.base.CustomViewModel;
import com.hongyuan.sellfitness.base.ItemViewModel;
import com.hongyuan.sellfitness.data.MyRepository;
import com.hongyuan.sellfitness.ui.person.beans.MyOrdersBean;
import java.util.List;

import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class MyOrdersViewModel extends CustomViewModel<MyRepository> {

    public MyOrdersViewModel(@NonNull Application application, MyRepository model) {
        super(application, model);
    }

    //给RecyclerView添加ObservableList
    public ObservableList<MyOrdersItemViewModel> observableList = new ObservableArrayList<>();

    //给RecyclerView添加ItemBinding
    public ItemBinding<MyOrdersItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_my_orders);

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //取消订单
        public SingleLiveEvent<Void> cancelOrder = new SingleLiveEvent<>();
    }

    @Override
    public void onResume() {
        super.onResume();

        requestData(Constants.GET_ORDER_LIST);
    }

    @Override
    protected void returnData(int code, Object dataBean) {
        super.returnData(code, dataBean);

        if(code == Constants.GET_ORDER_LIST){
            List<MyOrdersBean.ListBean> mList = ((MyOrdersBean)dataBean).getList();
            //清除旧数据
            if(curPage == FIRST_PAGE){
                observableList.clear();
            }

            if(mList != null && mList.size() > 0){
                for(MyOrdersBean.ListBean bean : mList){
                    MyOrdersItemViewModel itemViewModel = new MyOrdersItemViewModel(this,bean);
                    observableList.add(itemViewModel);
                }
            }

            if(observableList.size() > 0){
                if(mList == null || mList.size() == 0){
                    getUC().getFinishLoadMoreData().call();
                }
            }else{

            }
        }

        if(code == Constants.CANCEL_ORDER){
            if(itemViewModel != null){
                observableList.remove(itemViewModel);
            }
        }
    }

    //操作的子项
    public MyOrdersItemViewModel itemViewModel;

    @Override
    public void itemClick(ItemViewModel itemVM) {
        super.itemClick(itemVM);

        itemViewModel = (MyOrdersItemViewModel) itemVM;

    }

}
